package com.siecom.special;

import android.util.Log;

import com.siecom.framework.appinterface.APDU_RESP;
import com.siecom.framework.appinterface.APDU_SEND;
import com.siecom.framework.appinterface.Api;
import com.siecom.tools.ByteTool;

/**
 * Created by zhq on 2016/4/7.
 */
public class PbocEmv {
    private static PbocEmv module = new PbocEmv();
    private static final String TAG = "PbocEmv";
    private Api api;

    private PbocEmv() {
        api = new Api();

    }

    public static PbocEmv getInstance() {

        return module;

    }

    //卡片上电
    public int CardOpen() {
        byte[] ATR = new byte[100];
        int ret = api.Icc_Open((byte) 0x00, (byte) 0x01, ATR);
        return ret;
    }

    //检测卡片
    public int checkCard() {
        int iret = api.Icc_Detect((byte) 0x00);
        return iret;
    }

    public int selectPSE() {

        byte cmd[] = ByteTool.hexStr2Bytes("00A40400");
        String sendmsg = "1PAY.SYS.DDF01";
        short Lc = 0x0e;
        short Le = 256;
        APDU_SEND ApduSend = new APDU_SEND(cmd, Lc, sendmsg.getBytes(), Le);
        APDU_RESP ApduResp = new APDU_RESP();
        int ret = api.Icc_Command((byte) 0x00, ApduSend, ApduResp);
        if (ret != 0) {
            Log.e(TAG, "Icc_Command: ret = " + ret);
            return ret;
        }
        byte[] bf = new byte[ApduResp.LenOut];
        System.arraycopy(ApduResp.DataOut, 0, bf, 0, ApduResp.LenOut);
        Log.e("bf", ByteTool.byte2hex(bf));
        Log.e("SWA", ByteTool.byteToHexString(ApduResp.SWA));
        Log.e("SWB", ByteTool.byteToHexString(ApduResp.SWB));
        if (ApduResp.SWA != (byte) 0x90 || ApduResp.SWB != (byte) 0x00) {
            Log.e(TAG, "Icc_Command fail: ret = " + ret);
            return -1;
        } else {
            return 0;
        }
    }


}
